'use strict';

stareal
    .controller("VenusDetailController", function ($scope, $stateParams, $api, $sce, base64, $state, $alert,localStorageService,$lazyLoader,$interval, $http) {
        $scope.sharUrl='https://test.djx.m.opentickets.cn/?&#/'; // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致'
        if($stateParams.app==1){
            $scope.BackStatus=true;
            $scope.dowload_appStatus=true;
        }
        $scope.closedDowload=function(){
            $scope.dowload_appStatus=false;
        }
        $scope.id = $stateParams.id;
        $scope.longitude0=localStorageService.get('longitude');//当前的位置
        $scope.latitude0=localStorageService.get('latitude');//当前的位置
        $scope.goodfoods=[];
        $scope.dWITH=(document.body.clientWidth-320)/2;
        localStorageService.set('360Img','');
        //微信分享http://192.168.1.4:9090/oauth/getSignature
        $scope.getShare=function(){
            $api.get("app/share/getSignature",{url: window.location.href.split('#')[0]})
                .then(function (ret) {
                    if (ret) {
                        var data=ret.data;
                        wx.config({
                            debug: false,
                            appId: data.appid,
                            timestamp: data.timestamp,
                            nonceStr: data.nonceStr,
                            signature: data.signature,
                            jsApiList: [
                                'onMenuShareTimeline',
                                'onMenuShareAppMessage',
                                'onMenuShareQQ',
                                // 'onMenuShareWeibo',
                                'onMenuShareQZone'
                            ]
                        });
                        wx.ready(function(res){
                            //分享到朋友圈
                            // console.log(res);
                            wx.onMenuShareTimeline({
                                title: $scope.venusDetail.name, // 分享标题
                                desc: '我在独角秀分享了场馆座位全景图！', // 分享描述
                                link: $scope.sharUrl+'main/venusdetail/'+$stateParams.id+'/1', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: $scope.venusDetail.thumb, // 分享图标
                                success: function () {
                                    // 用户确认分享后执行的回调函数
                                    //alert('你好');
                                },
                                cancel: function () {
                                    // 用户取消分享后执行的回调函数
                                    // alert('你好....');
                                }
                            });
                            //分享给朋友
                            wx.onMenuShareAppMessage({
                                title: $scope.venusDetail.name, // 分享标题
                                desc: '我在独角秀分享了场馆座位全景图！', // 分享描述
                                link: $scope.sharUrl+'main/venusdetail/'+$stateParams.id+'/1', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: $scope.venusDetail.thumb, // 分享图标
                                type: '', // 分享类型,music、video或link，不填默认为link
                                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                                success: function () {
// 用户确认分享后执行的回调函数
                                    // alert('你好....');
                                },
                                cancel: function () {
// 用户取消分享后执行的回调函数
                                }
                            });
                            wx.onMenuShareQQ({
                                title: $scope.venusDetail.name, // 分享标题
                                desc: '我在独角秀分享了场馆座位全景图！', // 分享描述
                                link: $scope.sharUrl+'main/venusdetail/'+$stateParams.id+'/1', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: $scope.venusDetail.thumb, // 分享图标
                                success: function () {
// 用户确认分享后执行的回调函数
                                },
                                cancel: function () {
// 用户取消分享后执行的回调函数
                                }
                            });
                            wx.onMenuShareQZone({
                                title: $scope.venusDetail.name, // 分享标题
                                desc: '我在独角秀分享了场馆座位全景图！', // 分享描述
                                link: $scope.sharUrl+'main/venusdetail/'+$stateParams.id+'/1', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: $scope.venusDetail.thumb, // 分享图标
                                success: function () {
// 用户确认分享后执行的回调函数
                                },
                                cancel: function () {
// 用户取消分享后执行的回调函数
                                }
                            });
                        });
                        wx.error(function(res){
                            //console.log(res);
                            alert("微信分享接口配置失败");
                        });
                    }
                })
        }

        if($scope.longitude0==''||$scope.longitude0==undefined||$scope.longitude0==null) {
            var  map= new AMap.Map('position_center');
            //实例化城市
            var geolocation = null;
            map.plugin('AMap.Geolocation', function () {
                geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true,//是否使用高精度定位，默认:true
                    timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                    maximumAge: 0,           //定位结果缓存0毫秒，默认：0
                    convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                    showButton: true,        //显示定位按钮，默认：true
                    buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
                    buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                    showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
                    showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
                    panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
                    zoomToAccuracy:true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                });
                map.addControl(geolocation);
                geolocation.getCurrentPosition(function(status,result){
                    if(status=='complete'){
                        localStorageService.set('longitude',result.position.lng);
                        localStorageService.set('latitude',result.position.lat);
                    }else{
                        $alert.show('定位失败！');
                    }

                });
            });
        }
        //获取详情
        $api.get("app/site/findById", {id: $stateParams.id}, true)
            .then(function (ret) {
                var good=ret.data;
                good.detail = $sce.trustAsHtml(good.detail);
                $scope.venusDetail= good;
                $scope.longitude=good.longitude;
                $scope.latitude=good.latitude;
                $scope.getShare();
                AMap.service(["AMap.PlaceSearch"], function() {   // //住宿服务 10 餐饮服务 05
                    var placeSearch = new AMap.PlaceSearch({ //构造地点查询类
                        pageSize: 2,
                         type: '100100|100101|100102|100103|100104|100105|100201',
                        pageIndex: 1,
                        extensions:'all',
                        sortrule:1,
                        // deep_type:'Dining',
                        children:1
                    });

                    var cpoint = new AMap.LngLat($scope.longitude, $scope.latitude); //中心点坐标
                    placeSearch.searchNearBy('酒店', cpoint,1000, function (status, result) {
                       // console.log(status)
                        if(status=='complete'){
                           console.log(result);
                            var poiList=result.poiList;
                            var poisa=poiList.pois;
                            for(var i=0;i<poisa.length;i++){
                                if(poisa[i].tel!=''){
                                    var tel=poisa[i].tel.split(';')[0];
                                    poisa[i].tel=tel
                                }else{
                                    poisa[i].tel='暂无';
                                }

                            }
                            $scope.goodHotels=poisa;
                            $scope.$apply();
                        }else if(status=='no_data'){
                            $scope.hotelnodata=true;
                            $scope.$apply();
                        }else{
                            $scope.hotelnodata=true;
                            $scope.$apply();
                           $alert.show('高德Api出错了！');
                        }
                    });
                })
                $scope.getDistance=function(long,lat){
                    if(long==undefined||long==''||long==null||lat==undefined||lat==''||lat==null||$scope.latitude0==''||$scope.latitude0==null||$scope.latitude0==undefined){
                        return '暂无'
                    }else{
                        var p1 = [long, lat];
                        var p0 = [ $scope.longitude0,$scope.latitude0];
                        var dis = AMap.GeometryUtil.distance(p1, p0); //米
                        return (dis/1000).toFixed(2)+'km' ;
                    }

                }
                //美食
                AMap.service(["AMap.PlaceSearch"], function() {   // //住宿服务 10 餐饮服务 05
                    var placeSearch1 = new AMap.PlaceSearch({ //构造地点查询类
                        pageSize: 2,
                        type: '餐饮',
                        pageIndex: 1,
                        sortrule:1,
                        extensions:'all',
                        children:1
                    });

                    var cpoint = new AMap.LngLat($scope.longitude, $scope.latitude); //中心点坐标
                    placeSearch1.searchNearBy('餐饮', cpoint, 1000, function (status, result) {
                        if(status=='complete'){
                           console.log(result);
                            var poiList=result.poiList;
                           var poisa=poiList.pois;
                            for(var i=0;i<poisa.length;i++){
                                if(poisa[i].tel!=''){
                                    var tel=poisa[i].tel.split(';')[0];
                                    poisa[i].tel=tel
                                }else{
                                    poisa[i].tel='暂无';
                                }

                            }
                            $scope.goodfoods=poisa;
                            $scope.$apply();
                        }else if(status=='no_data'){
                            $scope.goodfoodsnodata=true;
                            $scope.$apply();
                        }else{
                            $scope.goodfoodsnodata=true;
                            $scope.$apply();
                            $alert.show('高德Api出错了！');
                        }

                    });
                })


            });
        //查看详情
        //获取区域场景svg  app/site/sitesvg
        $api.get("app/site/sitesvg", {id:$stateParams.id}, true)
            .then(function (ret) {
                $scope.venusDetailsvg=ret.data;
                $scope.venusDetailImg=ret.img[0];
                var a=1000/$scope.venusDetailImg.height*0.32;
                var ssx="matrix("+a+", 0, 0, "+a+",0,0)";
                $("#venusall").attr("transform",ssx);
                $("#venusbg").attr('width',$scope.venusDetailImg.width);
                $("#venusbg").attr('height',$scope.venusDetailImg.height);
            });

        //收藏   view/collection?viewid      1 代表场馆  2代表拼房车 3众筹活动 4攻略    type   收藏
        $scope.Raiseactivitycollection=function(){
            var  rs = "main.venusdetail-" + JSON.stringify({id: $stateParams.id});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            var ua = window.navigator.userAgent.toLowerCase();
            if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                if (isbind != 1 && openID != '') {
                    localStorageService.set('cleartoken', token);
                    localStorageService.set('token', '');
                    location.href = "#/main/register/" + encodeURIComponent(rs);
                    return false
                }
            }
            if (!localStorageService.get('token')) {
                var  rs = "main.venusdetail-" + JSON.stringify({id: $stateParams.id});
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    // 正式地址
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state="+encodeURIComponent(rs);
                } else {
                    location.href = "#/main/login/"+encodeURIComponent(rs);
                }
                return false;
            }
            $api.post('app/view/collection', {viewid: $stateParams.id,type:1}, true)
                .then(function (ret) {
                    if(ret.follow==1){
                        $alert.show('收藏成功!');
                        $scope.venusDetail.favor=1;
                    }else if(ret.follow==-1){
                        $alert.show('取消收藏!');
                        $scope.venusDetail.favor=0;
                    }else{
                        $alert.show("抱歉，系统出错!")
                    }

                })
        }
        //设置360
          $scope.set360Img=function(index,url){
            //console.log(index);
              var  rs = "main.venusdetail-" + JSON.stringify({id: $stateParams.id});
              var token=localStorageService.get('token');
              var isbind = localStorageService.get('isbind');
              var openID = localStorageService.get('openid');
              var ua = window.navigator.userAgent.toLowerCase();
              if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                  if (isbind != 1 && openID != '') {
                      localStorageService.set('cleartoken', token);
                      localStorageService.set('token', '');
                      location.href = "#/main/register/" + encodeURIComponent(rs);
                      return false
                  }
              }
              if (!localStorageService.get('token')) {
                  var  rs = "main.venusdetail-" + JSON.stringify({id: $stateParams.id});
                  var ua = window.navigator.userAgent.toLowerCase();
                  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                      // 正式地址
                      location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                          "appid=wxda73ac8ac7af1261&" +
                          "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                          "&response_type=code&scope=snsapi_userinfo&state="+encodeURIComponent(rs);
                  } else {
                      location.href = "#/main/login/"+encodeURIComponent(rs);
                  }
                  return false;
              }

            $('path').attr('opacity','1.0');
            $('path[data-id='+index+']').attr('opacity','0.5');
              localStorageService.set('360Img',url);
              $scope.Img=localStorageService.get('360Img');
              $scope.venus360Id=localStorageService.set('venus360Id',$scope.id );
              if($scope.Img==''){
                  $alert.show('请选择查看的区域!');
                  return false;
              }
              $state.go('main.venus360',{},true);
          }

    })
